import { ADD_TO_CART, ADD_COUNTER } from './mutation-types';

export default {
    //异步操作
    addCart(context, payload) {
        // payload 新添加的商品

        //方法1
        // let oldProduct = null
        // for (let item of state.cartList) {
        //     if (item.iid === payload.iid) {
        //         oldProduct = item
        //     }
        // }
        //方法2
        //indexOf 如果有返回-1
        // let index = state.cartList.indexOf(payload)
        //方法3
        //条件相等 返回该item
        //1、查找之前的数组是否有该商品
        return new Promise((resolve, reject) => {
            let oldProduct = context.state.cartList.find(item => { return item.iid === payload.iid })
            //2、判断oldProduct
            if (oldProduct) {
                // oldProduct.count += 1
                context.commit(ADD_COUNTER, oldProduct)
                resolve('当前的商品数量+1')
            } else {
                payload.count = 1
                // state.cartList.push(payload)
                context.commit(ADD_TO_CART, payload)
                resolve('添加了新的商品')
            }
        })
    }
}